package com.jinloes.webfit;

import com.jinloes.webfit.persistence.Person;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityNotFoundException;
import javax.security.sasl.AuthenticationException;
import java.util.List;

@Repository("personDao")
@SuppressWarnings("unchecked")
public class PersonDaoHiberate extends GenericDaoHibernate<Person> implements PersonDao {

	public PersonDaoHiberate() {
		super(Person.class);
	}

    public Person getPersonByUsername(String username) throws DataAccessException, EntityNotFoundException {
        List<Person> people = this.getHibernateTemplate().findByNamedParam("select people from Person people where people.username = :username", "username", username);
        if (people == null || people.size() <= 0)
            throw new EntityNotFoundException("Not person with username " + username + " found");
        return people.get(0);
    }

	public Person authenticatePerson(String username, String password) throws DataAccessException, AuthenticationException {
        List<Person> validUsers = this.getHibernateTemplate().findByNamedParam("select people from Person people where people.username = :username and people.password = :password",
                new String[] { "username", "password" }, new String[] { username, password });
        if (validUsers == null || validUsers.size() <= 0)
            throw new AuthenticationException("No users found");
        return validUsers.get(0);
    }

}
